<template>
  <div class="container">
    <div class="app-container">
      <div class="one">
        <el-button size="mini" type="primary" @click="showDialog = true"
          >添加角色</el-button
        >
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200px" label="角色">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            ></el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200px" label="启动">
          <!-- 自定义结构属性 -->
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <span v-else>
              {{
                row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              type="textarea"
              v-if="row.isEdit"
              v-model="row.editRow.description"
              size="mini"
            ></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 防止操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" @click="btnEditOK(row)" type="primary"
                >确认</el-button
              >
              <el-button size="mini" @click="row.isEdit = false" type="primary"
                >取消</el-button
              >
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnOwner(row.id)"
                >分配权限</el-button
              >
              <el-button size="mini" type="text" @click="btnEdit(row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  size="mini"
                  type="text"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页器 -->
      <el-row type="flex" align="moddel" justify="end" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        >
        </el-pagination>
      </el-row>
    </div>
    <!-- 放置弹层 -->
    <!-- <el-dialog :visible.sync="showDialog" title="新增角色" width="500px">
      <el-form lable-width="120px">
        <el-form-item label="角色属性">
          <el-input size="mini" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch size="mini"></el-switch>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-button size="mini" type="primary">确认</el-button>
              <el-button size="mini" type="primary">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog> -->
    <el-dialog
      width="500px"
      title="新增角色"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <!-- 表单内容 -->
      <el-form
        label-width="120px"
        :model="roleForm"
        :rules="rules"
        ref="roleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input style="width: 300px" size="mini" v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            size="mini"
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
            v-model="roleForm.description"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button @click="btnOk" type="primary" size="mini"
                >确定</el-button
              >
              <el-button @click="btnCancel" size="mini">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色弹出层 -->
    <el-dialog title="分配权限" :visible.sync="showRoleDialog">
      <el-tree
        check-strictly
        ref="perTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      >
      </el-tree>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="showRoleDialog = false"
            >取消</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRoleList,
  addRole,
  updateRole,
  delRole,
  getRoleDetail,
  assignPerm,
} from "@/api/role";
import { getPermissionList } from "@/api/permission";
import { transListToTreeData } from "@/utils";
export default {
  name: "Role",
  data() {
    return {
      roleForm: {
        name: "",
        description: "",
        state: 0, // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
      permIds: [],
      currentRoleId: null,
      permissionData: [],
      showRoleDialog: false,
      showDialog: false, //控制的弹层的显示
      list: [],
      pageParams: {
        page: 1, //第几页
        pagesize: 5, //每页多少条数据
        total: 0, //总数据
      },
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams);
      this.list = rows;
      this.pageParams.total = total;
      // 针对每一个行数据添加一个idEdit
      // 针对每一行数据添加一个编辑标记
      this.list.forEach((item) => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, "isEdit", false);
        this.$set(item, "editRow", {
          name: item.name,
          state: item.state,
          description: item.description,
        });
      });
    },
    //获取最新的页码  返回最新的数据
    changePage(page) {
      this.pageParams.page = page;
      this.getRoleList();
    },
    // 添加确定按钮的回调
    btnOk() {
      this.$refs.roleForm.validate(async (isOK) => {
        if (isOK) {
          await addRole(this.roleForm);
          this.$message.success("添加角色成功");
          this.getRoleList();
          this.btnCancel();
        }
      });
    },
    // 添加取消按钮的回调
    btnCancel() {
      // this.roleForm = "";
      // 重置表单数据
      this.$refs.roleForm.resetFields(); //重置表单数据
      this.showDialog = false;
    },
    btnEdit(row) {
      row.isEdit = true;
      // 更新缓存数据
      row.editRow.name = row.name;
      row.editRow.state = row.state;
      row.editRow.description = row.description;
    },
    // 点击编辑确认按钮的回调
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.state && row.editRow.description) {
        // 调用更新接口
        await updateRole({ ...row.editRow, id: row.id });
        // 更新成功
        this.$message.success("更新角色成功");
        // 更新显示数据  退出编辑状态
        row.name = row.editRow.name; // eslint的一校验 误判
        row.state = row.editRow.state; // eslint的一校验 误判
        row.description = row.editRow.description; // eslint的一校验 误判
        row.isEdit = false;
        // Object.assign(target, source)
        // Object.assign(row, {
        //   ...row.editRow,
        //   isEdit: false, // 退出编辑模式
        // });
      } else {
        this.$message.warning("角色和描述不能为空");
      }
    },
    //删除按钮的回调
    async confirmDel(id) {
      await delRole(id); // 后端删除
      this.$message.success("删除角色成功");
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--;
      this.getRoleList();
    },
    // 分配权限按钮的回调
    async btnOwner(id) {
      this.currentRoleId = id;
      const { permIds } = await getRoleDetail(id);
      this.permIds = permIds;
      const res = transListToTreeData(await getPermissionList(), 0);
      this.permissionData = res;
      this.showRoleDialog = true;
    },
    //分配权限确定按钮的回调
    async btnOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.perTree.getCheckedKeys(),
      });
      this.$message.success("分配角色完成");
      this.showRoleDialog = false;
    },
  },
};
</script>
<style scoped>
.one {
  padding: 10px;
}
</style>
